<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class ProjectCheckIn extends Model
{
    protected  $table='project_clock_in';

    protected $fillable = [
        'project_id',
        'begin',
        'end',
        'reward_time',
        'distance',
        'address',
        'addr',
        'code',
        'lng',
        'lat'
    ];

    protected $appends = array('address');

    public function getBeginAttribute() {
        if (isset($this->attributes['begin'])) {
            $date = new Carbon($this->attributes['begin']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setBeginAttribute($value) {
        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['begin'] = $date->toDateTimeString();
    }

    public function getEndAttribute() {
        if (isset($this->attributes['end'])) {
            $date = new Carbon($this->attributes['end']);
            return $date->getTimestamp();
        }

        return null;
    }

    public function setEndAttribute($value) {
        $date = new Carbon();
        $date->setTimestamp($value);
        $this->attributes['end'] = $date->toDateTimeString();
    }

    public function setAddressAttribute($value) {
        $this->attributes['lng'] = $value['lng'];
        $this->attributes['lat'] = $value['lat'];
        $this->attributes['addr'] = $value['address'];
    }

    public function getAddressAttribute() {
        if (!isset($this->attributes['lng'])) {
            return null;
        }
        return [
            'lng' => $this->attributes['lng'],
            'lat' => $this->attributes['lat'],
            'address' => $this->attributes['addr'],
        ];
    }


    public function project() {
        return $this->belongsTo('App\Models\Project', 'project_id', 'id');
    }
}
